package com.febers.ihealth

import android.Manifest
import android.content.pm.PackageManager
import android.os.Build
import android.view.View
import androidx.appcompat.widget.Toolbar
import androidx.core.app.ActivityCompat
import com.febers.ihealth.base.BaseActivity
import com.febers.ihealth.utils.AnalyzeUtil
import com.febers.ihealth.utils.ScreenShot
import com.febers.ihealth.utils.illnessList
import com.febers.ihealth.utils.toast
import kotlinx.android.synthetic.main.activity_analyze.*
import kotlinx.android.synthetic.main.toolbar_common.*

class AnalyzeActivity: BaseActivity() {

    private var permissionArray = arrayOf(Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE)
    private var permissionCode = 9527

    override fun initView() {
        btn_analyze_enter.setOnClickListener {
            finish()
        }
    }

    override fun afterCreate() {
        val illness = StringBuilder()
        illnessList.forEach {
            illness.append("$it，")
        }

        tv_illness.text = illness.removeRange(illness.length-1, illness.length)

        val map = AnalyzeUtil.analysis()
        progress_circular.visibility = View.GONE
        val medicines = StringBuilder()
//        map.values.flatten().distinct().forEach {
//            medicines.append("$it    ")
//        }
        map.forEachIndexed { index, s ->
            medicines.append("""
                ${index+1}. $s
                
            """.trimIndent())
        }
        tv_medicines.text = medicines
        btn_analyze_share.setOnClickListener{
            if (Build.VERSION.SDK_INT > Build.VERSION_CODES.LOLLIPOP) {

                if (ActivityCompat.checkSelfPermission(this, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
                    ScreenShot.share(this, "分享图片给好友")
                } else {
                    ActivityCompat.requestPermissions(this, permissionArray, permissionCode)
                }

            } else {
                ScreenShot.share(this, "分享图片给好友")
            }
        }
    }

    override fun onRequestPermissionsResult(
        requestCode: Int,
        permissions: Array<out String>,
        grantResults: IntArray
    ) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults)
        if (requestCode == permissionCode) {
            var grant = false
            grantResults.forEach {
                grant = it == PackageManager.PERMISSION_GRANTED
            }
            if (grant) {
                ScreenShot.share(this, "分享图片给好友")
            } else {
                toast("授权失败，无法分享")
            }
        }
    }

    override fun setView(): Int = R.layout.activity_analyze

    override fun setToolbar(): Toolbar? = toolbar_common

    override fun setToolbarTitle(): String? = "药物推荐"

}